package me.jzn.alib.utils;

import android.text.Editable;
import android.text.Html;

import androidx.core.text.HtmlCompat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.XMLReader;

/**
 * @author xqs @date 2020/12/8
 */
public class HtmlUtil {
    private static final Logger log = LoggerFactory.getLogger(HtmlUtil.class);

    public static final CharSequence toHtml(String rawHtml) {
        return HtmlCompat.fromHtml(rawHtml, HtmlCompat.FROM_HTML_MODE_LEGACY);
    }

    public static final CharSequence toHtml(String rawHtml, Html.ImageGetter imgGetter) {
        return HtmlCompat.fromHtml(rawHtml, HtmlCompat.FROM_HTML_MODE_LEGACY, imgGetter, null);
    }

    public static final CharSequence toHtml(String rawHtml, Html.ImageGetter imgGetter, Html.TagHandler... tagHandlers) {
        Html.TagHandler TH = null;
        if (tagHandlers != null) {
            if (tagHandlers.length == 1) {
                TH = tagHandlers[0];
            } else if (tagHandlers.length > 1) {
                TH = new Html.TagHandler() {
                    @Override
                    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
                        for (Html.TagHandler handler : tagHandlers) {
                            handler.handleTag(opening, tag, output, xmlReader);
                        }
                    }
                };
            }
        }
        return HtmlCompat.fromHtml(rawHtml, HtmlCompat.FROM_HTML_MODE_LEGACY, imgGetter, TH);
    }

    public static final String readTagText(String html, String tag) {
        return readTagText(html, tag, 0);
    }

    public static final String readTagText(String html, String tag, int startIdx) {
        int idx = html.indexOf(String.format("<%s", tag), startIdx);
        if (idx > -1) {
            int endIdx = html.indexOf(String.format("</%s>", tag), idx);
            if (endIdx > -1) {
                return html.substring(idx + tag.length() + 2, endIdx);
            }
        }
        return null;
    }
}
